//
//  SuggestionViewController.m
//  HelloWorld
//
//  Created by MJiao on 15/6/24.
//  Copyright (c) 2015年 MJiao. All rights reserved.
//

#import "SuggestionViewController.h"

#import "AFHTTPRequestOperationManager.h"
#import "MJRefresh.h"
#import "SuggestionPageModel.h"
#import "Suggestion.h"
#import "SuggestionTableViewCell.h"
#import "SuggestioinDetailController.h"
#import "KVNProgress.h"
#import "CommonUtils.h"

@interface SuggestionViewController ()


/** 用来显示的假数据 */
@property(strong, nonatomic) SuggestionPageModel *suggesstionPageModel;
@property(strong, nonatomic) Suggestion *didSelectedSuggestion;

@end

@implementation SuggestionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    NSLog(@"SuggestionViewController viewDidLoad");

    /**
    *  初始化数据集
    */
    if (!self.suggesstionPageModel) {
        self.suggesstionPageModel = [[SuggestionPageModel alloc] init];
        self.suggesstionPageModel.dataArray = [[NSMutableArray alloc] init];
    }

    /**
    *  去掉TableView每个cell之间的默认分割线
    */
    // self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;


    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.suggesstionPageModel.currentPage = 0;
        [self.suggesstionPageModel.dataArray removeAllObjects];
        [self processNetRequest];
    }];

    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.suggesstionPageModel.currentPage += 1;
        [self processNetRequest];
    }];

    self.tableView.footer.autoChangeAlpha = YES;
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    self.tableView.header.autoChangeAlpha = YES;

    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}

- (void)processNetRequest {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

    self.suggesstionPageModel.currentPage++;

    NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/require/queryUid?currentPage=%ld", (unsigned long)self.suggesstionPageModel.currentPage];

    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 结束刷新
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];

        NSInteger currentPage = [[responseObject objectForKey:@"currentPage"] integerValue];
        NSInteger allPage = [[responseObject objectForKey:@"allPage"] integerValue];

        self.suggesstionPageModel.currentPage = currentPage;
        self.suggesstionPageModel.allPage = allPage;

        NSArray *result = [responseObject objectForKey:@"result"];
        [result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSString *title = [obj objectForKey:@"title"];
            NSInteger userId = [[obj objectForKey:@"userId"] integerValue];
            NSString *userName = [obj objectForKey:@"userName"];
            NSInteger suggestionId = [[obj objectForKey:@"id"] integerValue];
            NSString *contents = [obj objectForKey:@"contents"];
            NSString *status = [obj objectForKey:@"status"];
            NSString *createTime = [obj objectForKey:@"createtime"];

            Suggestion *suggestion = [[Suggestion alloc] init];
            suggestion.title = title;
            suggestion.userId = userId;
            suggestion.userName = [userName isKindOfClass:[NSNull class]] ? nil : userName;
            suggestion.suggestionId = suggestionId;
            suggestion.contents = contents;
            suggestion.status = status;
            suggestion.createTime = createTime;

            [self.suggesstionPageModel.dataArray addObject:suggestion];
        }];
        //刷新table.footer显示状态
        [self refreshTableFooterShowStatus];
        [self.tableView reloadData];

    }    failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        self.suggesstionPageModel.currentPage--;
        if (self.suggesstionPageModel.currentPage <= 0) {
            self.suggesstionPageModel.currentPage = 0;
        }

        [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];
        // 结束刷新
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];

    }];
    // 进入刷新状态后会自动调用这个block
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //刷新table.footer显示状态
    [self refreshTableFooterShowStatus];
}

- (void)refreshTableFooterShowStatus {
    if (self.suggesstionPageModel == nil || self.suggesstionPageModel.dataArray == nil || [self.suggesstionPageModel.dataArray count] == 0) {
        [self.tableView.footer setHidden:YES];
    } else {
        [self.tableView.footer setHidden:NO];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // NSLog(@"self.data.count:%d",self.data.count);
    return self.suggesstionPageModel.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *ID = @"suggestionTableViewCellIdentifier";
    SuggestionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[SuggestionTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    [indexPath row];


    NSLog(@"SuggestionTableViewCell.frame.size.width:=%f", cell.frame.size.width);
    NSLog(@"tableView.frame.size.width:=%f", self.tableView.frame.size.width);

    Suggestion *suggestion = [self.suggesstionPageModel.dataArray objectAtIndex:[indexPath row]];

    NSString *title = [CommonUtils serializableIdObject:suggestion.title defaultValue:@""];
    NSString *contents = [CommonUtils serializableIdObject:suggestion.contents defaultValue:@""];
    NSString *userName = [CommonUtils serializableIdObject:suggestion.userName defaultValue:@""];

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    //"createtime": "2015-07-09 17:32:43",
    [dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:SS"];

    NSString *createTime = suggestion.createTime;
    @try {
        createTime = [CommonUtils compareCurrentTime:[dateFormat dateFromString:suggestion.createTime]];
    }
    @catch (NSException *exception1) {
        NSLog(@"Exception occurred: %@, %@", exception1, [exception1 userInfo]);
    }

    [cell.lbCreateTime setText:createTime];
    [cell.lbTitle setText:title];

    [cell.lbContent setText:contents];

    [cell.libUserName setText:userName];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.didSelectedSuggestion = self.suggesstionPageModel.dataArray[indexPath.row];
    NSLog(@"didSelectedSuggestion.title:%@", self.didSelectedSuggestion.title);

    [self performSegueWithIdentifier:@"SuggestinSegueIdentifer" sender:self];
}

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender {
    if ([sender isKindOfClass:[SuggestionTableViewCell class]]) {
        // prevent segue from occurring
        return NO;
    }
    // by default perform the segue transition
    return YES;
}

/**
*  <#Description#>
*
*  @param segue  <#segue description#>
*  @param sender <#sender description#>
*/
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"SuggestinSegueIdentifer"]) {
        SuggestioinDetailController *destination = segue.destinationViewController;

        [destination setSuggestion:self.didSelectedSuggestion];

    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
